package com.shiro.hello;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;

public class Hello {
    public static void main(String[] args) {
        /**
         * 1.获取SecurityManager
         */
        /**
         * 方式1，DefaultSecurityManager  + IniRealm
         */
        /*DefaultSecurityManager securityManager = new DefaultSecurityManager();
        IniRealm iniRealm = new IniRealm("classpath:hello_shiro.ini");
        securityManager.setRealm(iniRealm);*/

        /**
         * 方式2，Factory<SecurityManager> + DefaultSecurityManager + IniRealm
         */
       /* Factory<SecurityManager> factory = new IniSecurityManagerFactory();
        DefaultSecurityManager securityManager = (DefaultSecurityManager) factory.getInstance();
        IniRealm iniRealm = new IniRealm("classpath:hello_shiro.ini");
        securityManager.setRealm(iniRealm);*/

        /**
         * 方式3，Factory<SecurityManager> + SecurityManager
         */
        // 读取配置文件，初始化SecurityManager工厂
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:hello_shiro.ini");
        // 获取securityManager实例
        SecurityManager securityManager = factory.getInstance();


        /**
         *  2.开始认证身份        SecurityUtils   Subject
         */
        // 把securityManager实例绑定到SecurityUtils
        SecurityUtils.setSecurityManager(securityManager);
        // 得到当前执行的用户
        Subject currentUser = SecurityUtils.getSubject();
        try {
            //  为接收到的用户创建token令牌
            UsernamePasswordToken token = new UsernamePasswordToken("java1234", "12341111");
            // 身份认证令牌
            currentUser.login(token);
            System.out.println("身份认证成功！");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            System.out.println("身份认证失败！");
        }
        // 退出
        currentUser.logout();
    }

}
